package com.mask.auth.service;

import com.mask.auth.api.domain.LoginUser;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class CustomUserDetailsService implements UserDetailsService {

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // TODO: 实际项目中需要从数据库查询用户信息
        LoginUser loginUser = mockUser(username);
        if (loginUser == null) {
            throw new UsernameNotFoundException("用户名或密码错误");
        }

        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        // 添加角色
        Set<String> roles = loginUser.getRoles();
        if (roles != null) {
            authorities.addAll(roles.stream()
                .map(role -> new SimpleGrantedAuthority("ROLE_" + role))
                .collect(Collectors.toList()));
        }
        // 添加权限
        Set<String> permissions = loginUser.getPermissions();
        if (permissions != null) {
            authorities.addAll(permissions.stream()
                .map(SimpleGrantedAuthority::new)
                .collect(Collectors.toList()));
        }

        return new User(loginUser.getUsername(),
                loginUser.getPassword(),
                loginUser.isEnabled(),
                loginUser.isAccountNonExpired(),
                loginUser.isCredentialsNonExpired(),
                loginUser.isAccountNonLocked(),
                authorities);
    }

    // 模拟用户数据，实际项目中需要从数据库查询
    private LoginUser mockUser(String username) {
        HashSet<String> admin = new HashSet<String>();
        admin.add("ADMIN");
        HashSet<String> strings = new HashSet<>();
        strings.add("sys:user:view");
        strings.add("sys:user:edit");
        // 这里只是示例，实际项目中需要根据真实的用户数据来处理
        if ("admin".equals(username)) {
            LoginUser user = new LoginUser();
            user.setUserId(1L);
            user.setUsername(username);
            // 密码为123456
            user.setPassword("{noop}123456");
            user.setRoles(admin);
            user.setPermissions(strings);
            return user;
        }
        return null;
    }
} 